from django.shortcuts import render
from django.http.response import HttpResponse, JsonResponse
from django.views.generic import View, TemplateView


# TODO: 类视图
class Index(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse('首页')


class Book(View):
    def dispatch(self, request, *args, **kwargs):
        """
        不管是get请求还是post请求，都会走dispatch(request,*args,**kwargs)方法，所以如果实现这个方法，将能够对所有请求都处理到
        """
        print('%s dispatch.....' % request.method)
        return super(Book, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return HttpResponse('图书')

    def http_method_not_allowed(self, request, *args, **kwargs):
        """
        访问了View中没有定义的方法，那么就会把这个请求转发给http_method_not_allowed(request,*args,**kwargs)
        """
        response = JsonResponse({'msg': '%s 不支持%s访问' % (request.get_full_path(), request.method)})
        response.status_code = 405
        return response


class BookHandler(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'add_book.html')

    def post(self, request, *args, **kwargs):
        title = request.POST.get('title')
        content = request.POST.get('content')
        print('title：', title)
        print('content：', content)
        return HttpResponse('success')


class BookDetail(View):
    def get(self, request, book_id, *args, **kwargs):
        response = HttpResponse(content='图书ID：%s' % book_id)
        return response


class About(TemplateView):
    template_name = 'about.html'

    def get_context_data(self, **kwargs):
        context = {
            'phone': '1008611'
        }
        return context